package com.qingzhou.gen.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.mybatisflex.solon.service.impl.ServiceImpl;
import com.qingzhou.common.constants.GenConstant;
import com.qingzhou.common.enums.DictEnum;
import com.qingzhou.common.utils.FileUtil;
import com.qingzhou.common.web.api.ApiCodes;
import com.qingzhou.gen.config.GenConfig;
import com.qingzhou.gen.domain.GenTable;
import com.qingzhou.gen.domain.GenTableColumn;
import com.qingzhou.gen.mapper.GenTableMapper;
import com.qingzhou.gen.service.IGenTableColumnService;
import com.qingzhou.gen.service.IGenTableService;
import com.qingzhou.gen.utils.GenUtil;
import com.qingzhou.gen.utils.VelocityInitializer;
import com.qingzhou.gen.utils.VelocityUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.ibatis.solon.annotation.Db;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 业务表 服务层实现
 * @author xm
 */
@Component
public class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> implements IGenTableService {

    @Db
    GenTableMapper genTableMapper;

    @Inject
    IGenTableColumnService genTableColumnService;

    @Inject
    GenConfig genConfig;

    /**
     * 查询数据库列表
     * @param genTable
     * @return
     */
    @Override
    public List<GenTable> tables(GenTable genTable) {
        return genTableMapper.selectTables(genConfig.getIgnoreTablePrefix(), genTable);
    }

    /**
     * 查询代码生成详情
     * @param tableId
     * @return
     */
    @Override
    public Map<String, Object> info(Long tableId) {
        GenTable table = genTableMapper.selectGenTableById(tableId, DictEnum.DEL_FLAG.OK.getValue());
        setTableFromOptions(table);
        List<GenTable> tables = genTableMapper.selectGenTableAll(DictEnum.DEL_FLAG.OK.getValue());
        List<GenTableColumn> list = genTableColumnService.selectTableColumnListByTableId(tableId);
        Map<String, Object> map = new HashMap<>();
        map.put("info", table);
        map.put("rows", list);
        map.put("tables", tables);
        return map;
    }

    /**
     * 预览代码生成
     * @param tableId
     * @return
     */
    @Override
    public Map<String, String> preview(Long tableId) {
        Map<String, String> map = new LinkedHashMap<>();
        // 查询表信息
        GenTable table = genTableMapper.selectGenTableById(tableId, DictEnum.DEL_FLAG.OK.getValue());
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);
        VelocityInitializer.initVelocity();
        VelocityContext context = VelocityUtil.prepareContext(table);
        // 获取模板列表
        List<String> templates = VelocityUtil.getTemplateList(table.getTplCategory());
        for (String template : templates) {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, StandardCharsets.UTF_8.name());
            tpl.merge(context, sw);
            map.put(template, sw.toString());
        }
        return map;
    }

    /**
     * 新增代码生成（导入表）
     * @param tables
     */
    @Override
    public void add(String tables) {
        String[] tableNames = tables.split(",");
        // 查询表信息
        List<GenTable> tableList = genTableMapper.selectTablesByNames(tableNames);
        try {
            for (GenTable table : tableList) {
                // 保存表信息
                String tableName = table.getTableName();
                GenUtil.initTable(table, genConfig);
                int row = genTableMapper.insert(table);
                if (row > 0) {
                    // 保存列信息
                    List<GenTableColumn> genTableColumns = genTableColumnService.selectTableColumnsByName(tableName);
                    for (GenTableColumn column : genTableColumns) {
                        GenUtil.initColumnField(column, table);
                        genTableColumnService.save(column);
                    }
                }
            }
        } catch (Exception e) {
            throw ApiCodes.CODE_400(e);
        }
    }

    /**
     * 修改代码生成
     * @param genTable
     * @return
     */
    @Override
    public int edit(GenTable genTable) {
        // 修改保存参数校验
        String options = JSONUtil.toJsonStr(genTable.getParams());
        if (GenConstant.TPL_TREE.equals(genTable.getTplCategory())) {
            JSONObject paramsObj = JSONUtil.parseObj(options);
            if (StrUtil.isEmpty(paramsObj.getStr(GenConstant.TREE_CODE))) {
                throw ApiCodes.CODE_400("树编码字段不能为空");
            } else if (StrUtil.isEmpty(paramsObj.getStr(GenConstant.TREE_PARENT_CODE))) {
                throw ApiCodes.CODE_400("树父编码字段不能为空");
            } else if (StrUtil.isEmpty(paramsObj.getStr(GenConstant.TREE_NAME))) {
                throw ApiCodes.CODE_400("树名称字段不能为空");
            } else if (GenConstant.TPL_SUB.equals(genTable.getTplCategory())) {
                if (StrUtil.isEmpty(genTable.getSubTableName())) {
                    throw ApiCodes.CODE_400("关联子表的表名不能为空");
                } else if (StrUtil.isEmpty(genTable.getSubTableFkName())) {
                    throw ApiCodes.CODE_400("子表关联的外键名不能为空");
                }
            }
        }
        genTable.setOptions(options);
        int row = genTableMapper.update(genTable);
        if (row > 0) {
            for (GenTableColumn cenTableColumn : genTable.getColumns()) {
                genTableColumnService.updateById(cenTableColumn);
            }
        }
        return row;
    }

    /**
     * 删除代码生成
     * @param tableIds
     */
    @Override
    public void delete(Long[] tableIds) {
        genTableMapper.deleteGenTableByIds(tableIds);
        genTableColumnService.deleteGenTableColumnByIds(tableIds);
    }

    /**
     * 同步数据库
     * @param tableName
     */
    @Override
    public void synchDb(String tableName) {
        GenTable table = genTableMapper.selectGenTableByName(tableName, DictEnum.DEL_FLAG.OK.getValue());
        List<GenTableColumn> tableColumns = table.getColumns();
        Map<String, GenTableColumn> tableColumnMap = tableColumns.stream().collect(Collectors.toMap(GenTableColumn::getColumnName, Function.identity()));
        List<GenTableColumn> dbTableColumns = genTableColumnService.selectTableColumnsByName(tableName);
        if (CollectionUtil.isEmpty(dbTableColumns)) {
            throw ApiCodes.CODE_400("同步数据失败，原表结构不存在");
        }
        List<String> dbTableColumnNames = dbTableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList());
        dbTableColumns.forEach(column -> {
            GenUtil.initColumnField(column, table);
            if (tableColumnMap.containsKey(column.getColumnName())) {
                GenTableColumn prevColumn = tableColumnMap.get(column.getColumnName());
                column.setColumnId(prevColumn.getColumnId());
                if (column.isList()) {
                    // 如果是列表，继续保留查询方式/字典类型选项
                    column.setDictType(prevColumn.getDictType());
                    column.setQueryType(prevColumn.getQueryType());
                }
                if (StrUtil.isNotEmpty(prevColumn.getIsRequired()) && !column.isPk()
                        && (column.isInsert() || column.isEdit())
                        && ((column.isUsableColumn()) || (!column.isSuperColumn()))) {
                    // 如果是(新增/修改&非主键/非忽略及父属性)，继续保留必填/显示类型选项
                    column.setIsRequired(prevColumn.getIsRequired());
                    column.setHtmlType(prevColumn.getHtmlType());
                }
                genTableColumnService.updateById(column);
            } else {
                genTableColumnService.save(column);
            }
        });

        List<GenTableColumn> delColumns = tableColumns.stream().filter(column -> !dbTableColumnNames.contains(column.getColumnName())).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(delColumns)) {
            genTableColumnService.deleteGenTableColumns(delColumns);
        }
    }

    /**
     * 生成代码（自定义路径）
     * @param tableName
     */
    @Override
    public void genCode(String tableName) {
        // 查询表信息
        GenTable table = genTableMapper.selectGenTableByName(tableName, DictEnum.DEL_FLAG.OK.getValue());
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);
        VelocityInitializer.initVelocity();
        VelocityContext context = VelocityUtil.prepareContext(table);
        // 获取模板列表
        List<String> templates = VelocityUtil.getTemplateList(table.getTplCategory());
        for (String template : templates) {
            if (!StrUtil.containsAny(template, "sql.vm", "api.js.vm", "index.vue.vm", "index-tree.vue.vm")) {
                // 渲染模板
                StringWriter sw = new StringWriter();
                Template tpl = Velocity.getTemplate(template, StandardCharsets.UTF_8.name());
                tpl.merge(context, sw);
                try {
                    String path = getGenPath(table, template);
                    FileUtils.writeStringToFile(new File(path), sw.toString(), StandardCharsets.UTF_8.name());
                } catch (IOException e) {
                    throw ApiCodes.CODE_400("渲染模板失败，表名：" + table.getTableName());
                }
            }
        }
    }

    /**
     *
     * @param tables
     * @return
     */
    @Override
    public void batchGenCode(String tables) {
        String[] tableNames = Convert.toStrArray(tables);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (String tableName : tableNames) {
            generatorCode(tableName, zip);
        }
        IOUtils.closeQuietly(zip);
        FileUtil.download(outputStream);
    }

    /**
     * 设置主子表信息
     * @param table 业务表信息
     */
    public void setSubTable(GenTable table) {
        String subTableName = table.getSubTableName();
        if (StrUtil.isNotEmpty(subTableName)) {
            table.setSubTable(genTableMapper.selectGenTableByName(subTableName, DictEnum.DEL_FLAG.OK.getValue()));
        }
    }

    /**
     * 设置主键列信息
     * @param table 业务表信息
     */
    public void setPkColumn(GenTable table) {
        for (GenTableColumn column : table.getColumns()) {
            if (column.isPk()) {
                table.setPkColumn(column);
                break;
            }
        }
        if (ObjectUtil.isNull(table.getPkColumn())) {
            table.setPkColumn(table.getColumns().get(0));
        }
        if (GenConstant.TPL_SUB.equals(table.getTplCategory())) {
            for (GenTableColumn column : table.getSubTable().getColumns()) {
                if (column.isPk()) {
                    table.getSubTable().setPkColumn(column);
                    break;
                }
            }
            if (ObjectUtil.isNull(table.getSubTable().getPkColumn())) {
                table.getSubTable().setPkColumn(table.getSubTable().getColumns().get(0));
            }
        }
    }

    /**
     * 设置代码生成其他选项值
     * @param genTable
     */
    public void setTableFromOptions(GenTable genTable) {
        JSONObject paramsObj = JSONUtil.parseObj(genTable.getOptions());
        if (ObjectUtil.isNotNull(paramsObj)) {
            String treeCode = paramsObj.getStr(GenConstant.TREE_CODE);
            String treeParentCode = paramsObj.getStr(GenConstant.TREE_PARENT_CODE);
            String treeName = paramsObj.getStr(GenConstant.TREE_NAME);
            String parentMenuId = paramsObj.getStr(GenConstant.PARENT_MENU_ID);
            String parentMenuName = paramsObj.getStr(GenConstant.PARENT_MENU_NAME);

            genTable.setTreeCode(treeCode);
            genTable.setTreeParentCode(treeParentCode);
            genTable.setTreeName(treeName);
            genTable.setParentMenuId(parentMenuId);
            genTable.setParentMenuName(parentMenuName);
        }
    }

    /**
     * 获取代码生成地址
     * @param table 业务表信息
     * @param template 模板文件路径
     * @return
     */
    public static String getGenPath(GenTable table, String template) {
        String genPath = table.getGenPath();
        if (StrUtil.equals(genPath, "/")) {
            return System.getProperty("user.dir") + File.separator + "src" + File.separator + VelocityUtil.getFileName(template, table);
        }
        return genPath + File.separator + VelocityUtil.getFileName(template, table);
    }

    /**
     * 查询表信息并生成代码
     */
    private void generatorCode(String tableName, ZipOutputStream zip) {
        // 查询表信息
        GenTable table = genTableMapper.selectGenTableByName(tableName, DictEnum.DEL_FLAG.OK.getValue());
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);
        VelocityInitializer.initVelocity();
        VelocityContext context = VelocityUtil.prepareContext(table);
        // 获取模板列表
        List<String> templates = VelocityUtil.getTemplateList(table.getTplCategory());
        for (String template : templates) {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, StandardCharsets.UTF_8.name());
            tpl.merge(context, sw);
            try {
                // 添加到zip
                zip.putNextEntry(new ZipEntry(VelocityUtil.getFileName(template, table)));
                IOUtils.write(sw.toString(), zip, StandardCharsets.UTF_8.name());
                IOUtils.closeQuietly(sw);
                zip.flush();
                zip.closeEntry();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
